package com.chaosj.webmagic.convert;

import com.chaosj.webmagic.dto.SearchEnums;
import com.chaosj.webmagic.dto.SearchResponseDto;
import com.chaosj.webmagic.dto.idiomschina.LexIconResponseDto;
import com.google.common.base.Joiner;
import us.codecraft.webmagic.Page;

import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * @className: LexiconConvertHandler
 * @description:
 * @author: caoyangjie
 * @date: 2021/8/12
 **/
public class PoemChinaConvertHandler extends LexiconConvertHandler<LexIconResponseDto>{

    @Override
    public void convert(Page page) {
        if( first.compareAndSet(false, true) ){
            try{
                page.addTargetRequests(page.getHtml().xpath("//div[@class='service-content']//a/@href").all().subList(0,1));
            } finally {
                first.set(true);
            }
        }else{
            SearchResponseDto lexicon = createOrGet(page);
            page.getHtml().xpath("//div[@class='sons']").nodes().forEach(shiGe->{
                // 标题
                String title = shiGe.xpath("//b/text()").get();
                // 链接
                String target = holdTarget(shiGe.xpath("//a/@href").nodes().get(0).get());
                // 来源
                String source = Joiner.on(",").join(shiGe.xpath("//p[@class='source']//a/text()").all());
                String content = Optional.ofNullable(shiGe.xpath("//div[@class='contson']//div/text()").get()).orElse("").replaceAll("。","。\n");
                lexicon.addObject(title, target, source, content);
            });
        }
    }


    @Override
    public boolean support(SearchEnums instance) {
        return SearchEnums.POEM_CHINA.equals(instance);
    }

    @Override
    public String holdTarget(String target) {
        return SearchEnums.POEM_CHINA.getDomain()+target.substring(1);
    }
}
